package com.imti.mediaplayerdemo;

import android.Manifest;
import android.Manifest.permission;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnTimedTextListener;
import android.media.TimedText;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.tbruyelle.rxpermissions3.RxPermissions;
import io.reactivex.rxjava3.functions.Consumer;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity
{

    private MediaPlayer mPlayer;

    private ImageButton mBtnPlayPause;

    private ImageButton mBtnStop;

    private SeekBar mSeekProgress;

    private boolean isStoped = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new RxPermissions(this)
            .request(android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe(new Consumer<Boolean>()
            {
                @Override
                public void accept(Boolean aBoolean) throws Throwable
                {
                    if (aBoolean)
                    {
                        initView();
                    }
                }
            });
    }

    private void initView()
    {
        mBtnPlayPause = findViewById(R.id.btn_media_play_pause);
        mBtnStop = findViewById(R.id.btn_media_stop);
        mSeekProgress = findViewById(R.id.seek_media_progress);

        mBtnStop.setEnabled(false);

        initMedia();

        mBtnPlayPause.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //如果点击停止后再次点击播放按钮
                //则需要重新初始化MediaPlayer
                if (null == mPlayer)
                {
                    initMedia();
                }

                //根据当前播放状态，设置播放按钮图片
                mBtnPlayPause.setImageResource(
                    mPlayer.isPlaying() ?
                        R.drawable.ic_baseline_play_arrow_24
                        : R.drawable.ic_baseline_pause_24);

                if (mPlayer.isPlaying())
                {
                    pauseMusic();
                } else
                {
                    playMusic();
                }
            }
        });

        mBtnStop.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!isStoped)
                {
                    stopMusic();
                }
            }
        });
    }

    private void initMedia()
    {
        isStoped = false;
        mBtnStop.setEnabled(!isStoped);

        mPlayer = new MediaPlayer();

        //获取本地音频文件
        try
        {
            File musicFilePath = getLocalMusic();

            //MediaPlayer初始化
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(musicFilePath.getAbsolutePath());
            mPlayer.prepare();

            //设置当前媒体循环播放（单曲播放）
//            mPlayer.setLooping(true);

            //监听当前媒体是否播放完成
            mPlayer.setOnCompletionListener(new OnCompletionListener()
            {
                @Override
                public void onCompletion(MediaPlayer mp)
                {

                }
            });

            //拖动到具体播放时间
            mPlayer.seekTo(2500);

            //获取媒体总时长
            mPlayer.getDuration();

            //拖拽进度条的拖拽进度监听
            mSeekProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
            {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
                {

                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar)
                {

                }
                @Override
                public void onStopTrackingTouch(SeekBar seekBar)
                {

                }
            });

        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void playMusic()
    {
        if (!mPlayer.isPlaying())
        {
            mPlayer.start();
        }
    }

    private void pauseMusic()
    {
        if (mPlayer.isPlaying())
        {
            mPlayer.pause();
        }
    }

    private void stopMusic()
    {
        isStoped = true;
        mBtnStop.setEnabled(!isStoped);

        mBtnPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
        mPlayer.stop();
        mPlayer.reset();
        mPlayer.release();
        mPlayer = null;
    }

    private File getLocalMusic() throws IOException
    {
        if (Environment.MEDIA_MOUNTED.equals(
            Environment.getExternalStorageState()))
        {
            String rootPath =
                Environment.getExternalStorageDirectory().getCanonicalPath();

            File musicDir = new File(rootPath + "/Music");

            //获取外部存储中Music目录下的所有.mp3文件
            File[] musicFiles = musicDir.listFiles(new FileFilter()
            {
                @Override
                public boolean accept(File pathname)
                {
                    return pathname.getName().endsWith(".mp3");
                }
            });

            if (null == musicFiles)
            {
                return null;
            }
            return musicFiles[0];
        }
        return null;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();

        stopMusic();
    }
}